package com.github.niefy.modules.openapi.resource.filter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.github.niefy.common.exception.ErrorMessage;
import com.github.niefy.common.utils.EhCacheUtils;
import com.github.niefy.modules.third.entity.ThirdSysInfo;
import com.github.niefy.modules.third.service.ThirdSysInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * @author : [86188]
 * @description : 拦截对openApi的非法请求
 * @createTime : [2023/5/16 9:17]
 * @updateUser : [86188]
 * @updateTime : [2023/5/16 9:17]
 */
@Slf4j
@Component
public class OpenAccessTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private ThirdSysInfoService thirdSysInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        var accessToken = request.getHeader("wxapi-access-token");
        var appid = request.getHeader("wxapi-appid");
        //若系统未注册，直接返回
        var thirdSysInfo = thirdSysInfoService.lambdaQuery()
                .eq(ThirdSysInfo::getOpenAppid, appid)
                .one();
        if (BeanUtil.isEmpty(thirdSysInfo)){
            var resObj = ErrorMessage.messageToR("A0160");
            ServletUtil.write(response, JSONUtil.toJsonStr(resObj), ContentType.JSON.getValue());
            return false;
        }
        //系统已注册，校验token是否有效，有效放行并将系统信息放入request域
        String accessTokenCache = EhCacheUtils.get(appid,"appAccessServerTokenCache");
        if (!StrUtil.equals(accessToken, accessTokenCache)){
            var resObj = ErrorMessage.messageToR("A0311");
            ServletUtil.write(response, JSONUtil.toJsonStr(resObj), ContentType.JSON.getValue());
            return false;
        }
        request.setAttribute("wxAppid", thirdSysInfo.getWxAppid());
        request.setAttribute("openAppid", thirdSysInfo.getOpenAppid());
        return true;
    }
}
